package com.cykj.user.service.impl;
import com.cykj.system.api.domain.CtAddress;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.util.UriComponentsBuilder;
import com.cykj.common.core.utils.StringUtils;
import com.cykj.user.mapper.CtAddressMapper;
import com.cykj.user.service.IAddressService;
import org.apache.dubbo.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址服务实现
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Value("${baidu.map.ak}")
    private String baiduMapAk;

    @Autowired
    private CtAddressMapper addressMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public List<CtAddress> selectAddressList(Long customerId) {
        CtAddress address = new CtAddress();
        address.setCustomerId(customerId);
        return addressMapper.selectAddressList(address);
    }

    @Override
    public CtAddress selectAddressById(Long id) {
        return addressMapper.selectAddressById(id);
    }

    @Override
    public int insertAddress(CtAddress address) {
        // 如果是默认地址，先取消其他lp[默认地址
        if (address.getIsDefault() != null && address.getIsDefault()) {
            addressMapper.cancelDefaultAddress(address.getCustomerId());
        }
        return addressMapper.insertAddress(address);
    }

    @Override
    public int updateAddress(CtAddress address) {
        // 如果是默认地址，先取消其他默认地址
        if (address.getIsDefault() != null && address.getIsDefault()) {
            addressMapper.cancelDefaultAddress(address.getCustomerId());
        }
        return addressMapper.updateAddress(address);
    }

    @Override
    public int deleteAddressById(Long id) {
        return addressMapper.deleteAddressById(id);
    }

    @Override
    public int setDefaultAddress(Long id, Long customerId) {
        // 先取消所有默认地址
        addressMapper.cancelDefaultAddress(customerId);
        // 设置新的默认地址
        return addressMapper.setDefaultAddress(id);
    }

    @Override
    public Map<String, String> reverseGeocode(Double longitude, Double latitude) {
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/";
        Map<String, String> params = new HashMap<>();
        params.put("ak", baiduMapAk);
        params.put("output", "json");
        params.put("coordtype", "gcj02ll");
        params.put("location", latitude + "," + longitude);

        Map<String, String> result = new HashMap<>();
        try {
            String response = restTemplate.getForObject(
                    buildUrlWithParams(url, params),
                    String.class
            );
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = objectMapper.readValue(response, new TypeReference<Map<String, Object>>() {});
            if (data != null && data.get("result") != null) {
                Map<String, Object> resultData = (Map<String, Object>) data.get("result");
                Map<String, Object> addressComponent = (Map<String, Object>) resultData.get("addressComponent");
                
                result.put("region", addressComponent.get("province") + " " +
                    addressComponent.get("city") + " " + addressComponent.get("district"));
                result.put("address", resultData.get("formatted_address").toString());
                result.put("adcode", addressComponent.get("adcode").toString()); // 添加到返回Map


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    private String buildUrlWithParams(String url, Map<String, String> params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        params.forEach(builder::queryParam);
        return builder.build().toUriString();
    }

    @Override
    public Map<String, String> geocode(String address) {
        String url = "http://api.map.baidu.com/geocoding/v3/";
        Map<String, String> params = new HashMap<>();
        params.put("ak", baiduMapAk);
        params.put("output", "json");
        params.put("address", address);
        params.put("city", ""); // 可选：指定城市提高精度

        Map<String, String> result = new HashMap<>();
        try {
            String response = restTemplate.getForObject(
                    buildUrlWithParams(url, params),
                    String.class
            );
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = objectMapper.readValue(response, new TypeReference<Map<String, Object>>() {});

            if ("0".equals(data.get("status").toString())) {
                Map<String, Object> resultData = (Map<String, Object>) data.get("result");
                Map<String, Object> location = (Map<String, Object>) resultData.get("location");

                    result.put("longitude", location.get("lng").toString());
                result.put("latitude", location.get("lat").toString());
                result.put("precise", resultData.get("precise").toString()); // 精度标识
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // 扩展：支持周边检索的地址搜索
    @Override
    public List<Map<String, Object>> searchAddress(
            String keyword,
            String region,
            Double longitude,
            Double latitude,
            Integer radius) {
        String url = "http://api.map.baidu.com/place/v2/search";
        Map<String, String> params = new HashMap<>();
        params.put("ak", baiduMapAk);
        params.put("output", "json");
        params.put("query", keyword);
        params.put("page_size", "20");

        // 周边检索优先（如果有经纬度）
        if (longitude != null && latitude != null) {
            params.put("location", latitude + "," + longitude);
            params.put("radius", radius != null ? radius.toString() : "3000"); // 默认3公里
        } else {
            params.put("region", StringUtils.isNotEmpty(region) ? region : "全国");
        }

        try {
            String response = restTemplate.getForObject(
                    buildUrlWithParams(url, params),
                    String.class
            );
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = objectMapper.readValue(response, new TypeReference<Map<String, Object>>() {});

            if ("0".equals(data.get("status").toString())) {
                return (List<Map<String, Object>>) data.get("results");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}